<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Backup extends CIC_A_Controller
{
	var $path;
	var $conn;
	function __construct()
	{
		parent::__construct();
		$this->init();
	}
	
	private function init()
	{
		$this->path = 'public/admin/backup/';
		$this->load->dbutil();
		$this->load->helper('file');
	}

	
	function index()
	{
		$data['tables'] = $this->cic_model->query('select concat(truncate(DATA_LENGTH/1024,2),"KB") as DATA_SIZE,TABLE_NAME,UPDATE_TIME,TABLE_ROWS from information_schema.tables where table_schema="'.$this->db->database.'"');
		$this->load->view('admin/backup/index',$data);
	}
	
	function do_backup()
	{
		$prefs = array(
				'tables'      => $this->input->post('table_name'),  // 包含了需备份的表名的数组.
				'format'      => 'txt',
		);
		$backup = $this->dbutil->backup($prefs);
		$path = $this->path.'backup_'.time().'.sql';
		if(write_file($path, $backup))
		{
			$this->message->msg('备份成功！备份路径：'.$path,site_url('admin/backup/index'),5);
		}else{
			$this->message->msg('备份失败！',site_url('admin/backup/index'));
		}
	}
	
	function repair()
	{
		$this->load->helper('directory');
		$data['backup_file'] = directory_map($this->path,1);
		$this->load->view('admin/backup/repair',$data);
	}
	
	function do_repair()
	{
		$sqls = read_file($this->path.urldecode($this->uri->segment(4)));
		$sqls = preg_split('/;\s/', $sqls);
		array_pop($sqls);
		$error = '';
		foreach ($sqls as $value)
		{
			if(! $this->cic_model->query($value))
			{
				$error .= '<li>sql语句：'.$value.'处理失败！</li>';
			}
		}
		if($error == '')
		{
			$this->message->msg('恢复数据成功！',site_url('admin/backup/repair'));
		}else{
			$this->message->msg($error,site_url('admin/backup/repair'),10);
		}
	}
	
	function delete_backup()
	{
		if(unlink('./public/admin/backup/'.urldecode($this->uri->segment(4))))
		{
			$this->message->msg('删除成功！',site_url('admin/backup/repair'));
		}else{
			$this->message->msg('删除失败！',site_url('admin/backup/repair'));
		}
	}
}